#include "../include/buffer.h"
#define		MAX_BUFFER	2000
/* Funciones privadas */

/* Devuelve el caracter ingresado primero */
static int GetKey(void);
/* Indica si el buffer esta lleno */
int BufferIsFull(void);

static char buffer[MAX_BUFFER+1];
static int head = 0;
static int tail = 0;
static int buffer_ready;


int
BufferIsFull(void)
{
	return ((tail + 1) % (MAX_BUFFER + 1) == head);
}

int
BufferIsEmpty(void)
{
	return (head == tail);
}

int
InsertKey(char c)
{
	if (BufferIsFull())
		return -1;
	
	/* Si me llega un enter el buffer esta listo */
	if (c != 8)
	{	
	buffer[tail] = c;
	tail = (tail + 1) % (MAX_BUFFER + 1);
	}
	else
	{

	RemoveKey();
	buffer[tail] = ' ';
	}
	if (c == '\n')
		buffer_ready = 1;

	return c;
}

static int
GetKey(void)
{
	char c = 0;

	if (!BufferIsEmpty())
	{
		c = buffer[head];
		head = (head + 1) % (MAX_BUFFER + 1);
	}
	return c;
}	

void
RemoveKey(void)
{
	if (!BufferIsEmpty())
		tail = (tail - 1) % (MAX_BUFFER + 1);
}

int
FlushBuffer(char *output)
{
	int i = 0;

	while (!BufferIsEmpty())
	{
		output[i] = GetKey();
		if(output[i] == '\n')
		      output[i] = '\0';
		i++;
	}
	
	buffer_ready = 0;
	return i;
}

int
BufferIsReady(void)
{
	return (buffer_ready);
}

